package ru.ognick.core;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.json.JSONException;

import ru.ognick.R;
import ru.ognick.locale.ILocale;
import ru.ognick.locale.Locale;
import ru.ognick.logic.Praxis;
import ru.ognick.logic.Training;
import ru.ognick.utils.Conf;
import ru.ognick.utils.FileManager;
import ru.ognick.utils.Media;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Chronometer;
import android.widget.Chronometer.OnChronometerTickListener;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TabHost;
import android.widget.TextView;

public class ProcessManager {
    public static final String TAG = "TrainingLoader";
    private ArrayList<BundleProcess> bundleTraningElementList = new ArrayList<BundleProcess>();
    private final CoachActivity own;
    private TextToSpeech textToSpeech = null;
    private int currentTraining = -1;
    private CountDownTimer timer = null;
    private Media mediaPlayer;
    private File curFile = null;
    private final ILocale L = Locale.get();
    
        
    public ProcessManager(final CoachActivity own) {
		this.own = own;
		mediaPlayer = new Media(own);
    }
    
    public void saveState(Bundle state){
    	TabHost tabs = (TabHost) own.findViewById(R.id.tabhost);
    	final int curTab = tabs.getCurrentTab();
    	state.putInt("curTab", curTab);
		state.putInt("currentTraining", currentTraining);
		if (curFile != null)
			state.putString("curFile", curFile.getAbsolutePath());
    }
    
    public void restoreState(Bundle state){
    	final int curTab = state.getInt("curTab",1);

		final TabHost tabs = (TabHost) own.findViewById(R.id.tabhost);
		tabs.setCurrentTab(curTab);
		currentTraining = state.getInt("currentTraining", -1);
		String curNameFile = state.getString("curFile");
		if (curNameFile != null) {
			curFile = new File(curNameFile);
			load();
		}
    	switch (curTab) {
		case 0:
			break;
		default:
			break;
		}
    }
    
    public void finalize() {
		Conf.setLastTraing(curFile);
    	mediaPlayer.stop();
    }
    
    public void load() {
    	if (curFile != null) {
    		load(curFile);
   			pause();
    	}
    }
    
	public void load(File file) {
		if (curFile != file) 
			currentTraining = -1;
		curFile = file;
		bundleTraningElementList.clear();
		try {
			if (textToSpeech == null) {
				textToSpeech = new TextToSpeech(own, null);
				textToSpeech.setPitch(1f);
			}
			Training training = FileManager.loadTraining(file);
			for (final Praxis praxis : training) {
				LinearLayout linearLayout = new LinearLayout(own);
				linearLayout.setOrientation(LinearLayout.VERTICAL);
				
	        	LinearLayout topLayout = new LinearLayout(own);
	        	topLayout.setOrientation(LinearLayout.HORIZONTAL);
				
	        	final Chronometer chronometer = new Chronometer(own);
	        	chronometer.setBase(SystemClock.elapsedRealtime());
	        	chronometer.setTag("CHRONOMETR");
	        	
	        	View separator = new View(own);
	        	LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
	        	params.width = 10;
	        	separator.setLayoutParams(params);
	        	
	        	final TextView title = new TextView(own);
	        	title.setText(praxis.getTitle()+", "+praxis.getTimeSpan()+" "+L.G_SECOND());
//	        	title.setTextSize(title.getTextSize() + 5);
	        	title.setTextColor(Color.GRAY);
	        	title.setTypeface(null, Typeface.BOLD);
	        	title.setTag("TITLE");
        	
	        	TextView content = new TextView(own);
	        	content.setText(praxis.getContent());
	        	content.setTypeface(null, Typeface.ITALIC);
	        	content.setTag("CONTENT");
	        	
	        	final ProgressBar progressBar = new ProgressBar(own, null, android.R.attr.progressBarStyleHorizontal);	
	        	progressBar.setTag("PROCESS_BAR");
	        	progressBar.setMax(praxis.getTimeSpan());
	        	progressBar.setProgress(0);
	        	
	        	topLayout.addView(chronometer);
	        	topLayout.addView(separator);
	        	topLayout.addView(title);
	        	
	        	linearLayout.addView(topLayout);
	        	linearLayout.addView(content);
	        	linearLayout.addView(progressBar);

	        	final int index = bundleTraningElementList.size();
	        	final BundleProcess bundleProcess = new BundleProcess(index, praxis, linearLayout); 
				bundleTraningElementList.add(bundleProcess);
				
				final ProcessManager self = this;
				
				chronometer.setOnChronometerTickListener(new OnChronometerTickListener() {
				
					public void onChronometerTick(Chronometer chronometer) {
						if (bundleProcess.incProgress()) {
							int period = bundleProcess.getPeriodSpeak();
							if (period > 0)
								textToSpeech.speak(
										String.valueOf(period*praxis.getPeriodSignal())+" second", 
										TextToSpeech.QUEUE_FLUSH, null);
						}
						else {
							chronometer.stop();
							mediaPlayer.stop();
							textToSpeech.speak("Praxis finished!", TextToSpeech.QUEUE_FLUSH, null);
							timer = new CountDownTimer(2000,1) {
							
								public void onFinish() {
									try {
										self.OnClick(bundleTraningElementList.get(index + 1));
									}
									catch (IndexOutOfBoundsException e) {
										textToSpeech.speak("Ok! Training finished!", TextToSpeech.QUEUE_FLUSH, null);
									}
									
								}
							
								public void onTick(long millisUntilFinished) {
								}
								
							};
							timer.start();
						}
					}
				});
				
	        	title.setOnClickListener(new OnClickListener() {
				
					public void onClick(View v) {
						self.OnClick(bundleProcess);

					}
				});
	        	show();
			}
			
		} catch (IOException e) {
			Log.e(TAG,e.getMessage());
		} catch (JSONException e) {
			Log.e(TAG,e.getMessage());
		}
	}
	
	private void show() {
        LinearLayout linearLayoutOwn = (LinearLayout) own.findViewById(R.id.linearLayout1);
        if (linearLayoutOwn != null && bundleTraningElementList != null) {
        	linearLayoutOwn.removeAllViewsInLayout();
			for (BundleProcess bundleProcess : bundleTraningElementList)
	        	linearLayoutOwn.addView(bundleProcess.getElements());
        }
	}
	
    public void pause(){
        if (currentTraining >= 0 && currentTraining < bundleTraningElementList.size()) 
                OnClick(bundleTraningElementList.get(currentTraining));
    }

	
	private void OnClick(BundleProcess el){
		Log.d(TAG,String.valueOf(el.getIndex()));
		
		if (timer != null) {
			timer.cancel();
			textToSpeech.stop();
		}
		
		for (int i=0; i < bundleTraningElementList.size(); ++i){
			final BundleProcess bundleProcess = bundleTraningElementList.get(i);
			final Praxis praxis  = bundleProcess.getPraxis();
			LinearLayout elements = bundleProcess.getElements();
			final Chronometer chronometer = (Chronometer) elements.findViewWithTag("CHRONOMETR");
			TextView title = (TextView) elements.findViewWithTag("TITLE");
			TextView content = (TextView) elements.findViewWithTag("CONTENT");
			mediaPlayer.stop();
			chronometer.stop();
			
			if ( i < el.getIndex()) {
				title.setTextColor(Color.BLUE);
			} 
			else {
				bundleProcess.resetProgress();
				chronometer.setBase(SystemClock.elapsedRealtime());
				if (i == el.getIndex()) {
					ScrollView scrollView =  (ScrollView) own.findViewById(R.id.scrollView1);
					scrollView.requestChildFocus(elements, elements);
					if (currentTraining == i) {
						title.setTextColor(Color.RED);
						currentTraining = -1;
						textToSpeech.stop();
					}
					else {
						title.setTextColor(Color.GREEN);
						currentTraining = i;
						textToSpeech.speak(L.toSpeech((String) title.getText()), TextToSpeech.QUEUE_FLUSH, null);
						textToSpeech.speak(L.toSpeech((String) content.getText()), TextToSpeech.QUEUE_ADD, null);
						timer = new CountDownTimer(1000 * praxis.getTimePreload() ,1) {
						
							public void onTick(long millisUntilFinished) {
								
							}
						
							public void onFinish() {
//								mediaPlayer.stop();
								chronometer.setBase(SystemClock.elapsedRealtime());
								textToSpeech.speak("Start!", TextToSpeech.QUEUE_FLUSH, null);
								Runnable thread = new Runnable() {
								
									public void run() {
										chronometer.start();
										mediaPlayer.play(praxis.getMedia());	
									}
								};
								thread.run();
							}
						};
						timer.start();
					}
				}
				else {
					title.setTextColor(Color.GRAY);
				}
				
			}
		}
	}
	


}
